<?php
/**
 * Absract IQ roster object 
 * 
 * @packege stanza.iq.roster
 */
abstract class Zend_Jabber_Stanza_Response_Iq_Roster_Abstract extends Zend_Jabber_Stanza_Response_Iq_Abstract {    
    /**
     * Fill roster object with received items
     * 
     * @param Zend_Jabber_AddressBook $roster Roster object
     */
    public function createRostersItems(Zend_Jabber_AddressBook $roster) {
        $defaultCategoryName = $roster->getDefaultGroup()->getName();
        
        $groups  = array();
        foreach($roster->getGroups() as $group) {
            $groups[$group->getName()] = $group;
        }
       
        if($this->iqNode->firstChild && $this->iqNode->firstChild->hasChildNodes()) {
	        foreach($this->iqNode->firstChild->childNodes as $itemNode) {
	            $subscription = $itemNode->getAttribute('subscription');
	            $jid = $itemNode->getAttribute('jid');
	            $alias = $itemNode->getAttribute('name');
	            $friend = Zend_Jabber_User::getInstance($jid, empty($alias) ? false : $alias);
	            
	            $itemGroups = array();
	            $groupNodes = $itemNode->getElementsByTagName('group');
	            if($groupNodes->item(0)) {
		            foreach($groupNodes as $groupNode) {
		                $groupName = $groupNode->nodeValue;
		                if(!isset($groups[$groupName])) {
		                    $groups[$groupName] = new Zend_Jabber_AddressBook_Group($roster, $groupName);
		                }
		                
		                $itemGroups[] = $groups[$groupName];
		            }
	            } else {
	                $itemGroups[] = $groups[$defaultCategoryName];
	            }
	            
	            $item = new Zend_Jabber_AddressBook_Item($roster, $friend, $subscription, $itemGroups);
	            if($item->getSubscription() == Zend_Jabber_AddressBook_Item::SUBSCRIPTION_REMOVE) {
	                $roster->removeItem($item);
	            } else {
		            foreach($roster->getGroups() as $group) {
		                $group->removeItem($item);
		                if($group->countItems() == 0) {
		                    $roster->removeGroup($group);
		                }
		            }
		            foreach($itemGroups as $group) {
		                $group->addItem($item);
		            }
	            }
	        }
        }
        
        foreach($groups as $group) {
            if(!$roster->getGroupByName($group->getName()) && $group->countItems() > 0) {
                $roster->addGroup($group);
            }
        }
        
        return $roster;
    }
}
?>